package com.qiangesoft.datasourcepro.core;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 多数据源处理
 *
 * @author qiangesoft
 * @date 2024-03-14
 */
@Slf4j
@Order(1)
@Aspect
@Component
public class DataSourceAspect {

    /**
     * 切点
     */
    @Pointcut("@annotation(com.qiangesoft.datasourcepro.core.DataSource)")
    public void pointCut() {
    }

    /**
     * 通知
     *
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        DataSource dataSource = this.getDataSource(joinPoint);
        if (dataSource == null) {
            DataSourceContext.setDataSource("default");
        } else {
            DataSourceContext.setDataSource(dataSource.value());
        }
        try {
            return joinPoint.proceed();
        } finally {
            DataSourceContext.removeDataSource();
        }
    }

    /**
     * 获取数据源
     *
     * @param joinPoint
     * @return
     */
    public DataSource getDataSource(ProceedingJoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 方法上查找注解
        DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
        if (Objects.nonNull(dataSource)) {
            return dataSource;
        }
        // 类上查找注解
        return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
    }
}
